<?php

namespace App\Services;

use App\Dao\AnchorDao;
use App\Dao\AppUpgradeDao;
use App\Dao\Mongodb\UserChatV2Dao;
use App\Dao\PayCallDao;
use App\Dao\UserBlacklistDao;
use App\Job\Notification\UMengMsgPushJob;
use App\Job\YunXin\YunXinBatchSendAttachMsgJob;
use App\Job\YunXin\YunXinCallMsgJob;
use App\Job\YunXin\YunXinCustomMsgJob;
use App\Job\YunXin\YunXinSendAttachMsgJob;
use App\Job\YunXin\YunXinSendMsgJob;
use App\Job\YunXin\YunXinUserOnlineStatusJob;
use App\Model\User;
use App\Model\UserBlacklist;
use App\Utils\LoggerUtil;

class PushMessageService
{

    /**
     * 添加消息到发送队列
     * @param $uid
     * @param $message
     * @param string $package
     * @param int $from_uid
     * @return bool
     */
    public static function putUMengMsgQueue($uid, $message, $package = '', $from_uid = 0)
    {
        try {
            $result = pushQueueMessage(UMengMsgPushJob::class,
                array(
                    'uid' => $uid,
                    'message' => $message,
                    'package' => $package,
                    'from_uid' => $from_uid
                )
            );
            if (!$result) {
                throw new \Exception("加入发送队列失败");
            }
            return true;
        } catch (\Throwable $e) {
            LoggerUtil::write('put_umeng_send_attach_msg', [
                $e->getFile(), $e->getLine(), $e->getMessage()
            ]);
            return false;
        }
    }

    /**
     * 加入系统消息单发队列
     * @param $fromUid
     * @param $toUid
     * @param $message
     * @return mixed|string
     */
    public static function putYunXinSendAttachMsgQueue($fromUid, $toUid, $message)
    {
        try {
            if (is_array($message)) {
                $message = json_encode($message, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            }
            // $result = $this->queueService->push(new AttachMsgQueueJob(json_encode(["fromUid" => $fromUid, "toUid" => $toUid, "message" => $message])));
            $result = pushQueueMessage(YunXinSendAttachMsgJob::class, ["fromUid" => $fromUid, "toUid" => $toUid, "message" => $message]);
            if (!$result) {
                throw new \Exception("加入发送队列失败");
            }

            return true;
        } catch (\Throwable $e) {
            LoggerUtil::write('put_yun_xin_send_attach_msg', [
                $e->getFile(), $e->getLine(), $e->getMessage()
            ]);
            return false;
        }
    }


    /**
     * 通话相关im 单发队列
     * @param $fromUid
     * @param $uidList
     * @return mixed|string
     */
    public static function putYunXinCallMsgQueue($fromUid, $uidList)
    {
        try {
            $payCallDao = PayCallDao::getInstance();
            foreach ($uidList as $uid) {
                $lastMessage = $payCallDao->getLastMessagePayCall($uid);
                if (!empty($lastMessage['data'])) {
                    foreach ($lastMessage['data'] as $msg) {
                        $message = json_encode(array('event' => 'user_conn', 'client_uid' => $uid, 'msg' => [$msg], 'desc' => '获取成功'));
                        $result = pushQueueMessage(YunXinCallMsgJob::class, ["fromUid" => $fromUid, "toUid" => $uid, "message" => $message]);
                        if (!$result) {
                            throw new \Exception("加入发送队列失败");
                        }
                    }
                }
            }
            return true;
        } catch (\Throwable $e) {
            LoggerUtil::write('put_yun_xin_call_msg', [
                $e->getFile(), $e->getLine(), $e->getMessage()
            ]);
            return false;
        }
    }


    /**
     * Note - 添加刷新用户在线状态队列数据
     * DateTime 2024/7/30 12:30
     * User Admin
     * @param $fromUid
     * @param $toUids
     * @param $message
     * @return bool
     */
    public static function putYunXinUserOnlineStatus($fromUid, $toUids, $message)
    {
        try {
            $result = pushQueueMessage(YunXinUserOnlineStatusJob::class, compact("fromUid", "toUids", "message"));
            if (!$result) {
                throw new \Exception("putYunXinUserOnlineStatus加入发送队列失败");
            }
            return true;
        } catch (\Throwable $e) {
            LoggerUtil::write('put_yun_xin_user_online_status', [
                $e->getFile(), $e->getLine(), $e->getMessage()
            ]);
            return false;
        }
    }


    /**
     * Note - 添加 点对点普通自定义消息队列 数据
     * DateTime 2024/7/31 15:50
     * User Admin
     * @param $fromUid
     * @param $toUid
     * @param $message
     * @return bool
     */
    public static function putYunXinCustomMsgQueue($fromUid, $toUid, $message)
    {
        try {
            $result = pushQueueMessage(YunXinCustomMsgJob::class, compact("fromUid", "toUid", "message"));
            if (!$result) {
                throw new \Exception("putYunXinCustomMsg加入发送队列失败");
            }
            return true;
        } catch (\Throwable $e) {
            LoggerUtil::write('put_yun_xin_custom_msg', [
                $e->getFile(), $e->getLine(), $e->getMessage()
            ]);
            return false;
        }
    }


    /**
     * Note - 加入点对点普通文本消息队列
     * DateTime 2024/8/14 17:32
     * User Admin
     * @param $fromUid
     * @param $toUid
     * @param $content
     * @param $content_type
     * @param $chat_type
     * @param $audio_time
     * @param $msg_type
     * @param $ctime
     * @return bool
     */
    public static function putYunXinSendMsgQueue($fromUid, $toUid, $content, $content_type = 1, $chat_type = 29, $audio_time = 0, $msg_type = 0, $ctime = 0)
    {
        try {
            // $model = new \AppupgradeModel();
            // $senderUser = $model->find("id,status,sex,is_faceAuth", "id=?", [$fromUid], '', 'tb_user');
            $senderUser = User::query()->select(['id', 'status', 'sex'])->where('id', $fromUid)->first();
            $senderUser = modelToArray($senderUser);
            if (!$senderUser) {
                throw new \Exception("发送方不存在");
            }
            if ($senderUser['status'] != "0") {
                throw new \Exception("发送方已被禁言");
            }
            // $receiver = $model->find("`id`, `nickname`, `head_image`, `from`, `version_code`, `channel`, `last_login_ip`, `is_disturb`", "id = ?", [$toUid], '', 'tb_user');
            $receiver = User::query()->select(['id', 'nickname', 'head_image', 'from', 'version_code', 'channel', 'last_login_ip', 'is_disturb'])->where('id', $toUid)->first();
            $receiver = modelToArray($receiver);
            if (!$receiver) {
                throw new \Exception("接收方不存在");
            }
            if ((new AppUpgradeDao())->isHideMaleChatCost($receiver["from"], $receiver['version_code'], $receiver['channel'], $receiver['last_login_ip'], $toUid)) {
                throw new \Exception("接收方在审核环境中");
            }
            if (UserBlacklistDao::getInstance()->inBlackList($fromUid, $toUid)) {
                throw new \Exception("你已拉黑对方或对方已拉黑你");
            }

            $result = pushQueueMessage(YunXinSendMsgJob::class, compact("fromUid", "toUid", "content", "content_type", "chat_type", "audio_time", "msg_type", "ctime"));
            if (!$result) {
                throw new \Exception("putYunXinSendMsg加入发送队列失败");
            }
            return true;
        } catch (\Throwable $e) {
            LoggerUtil::write('put_yun_xin_send_msg', [
                $e->getFile(), $e->getLine(), $e->getMessage()
            ]);
            return false;
        }
    }


    /**
     * Note - 添加 礼物发送消息队列
     * DateTime 2024/8/19 14:53
     * User Admin
     * @param $user_id
     */
    public static function putYunXinSendGiftQueue($user_id)
    {
        try {
            $lastMessage = UserChatV2Dao::getInstance()->getLastMessage($user_id);
            if (!empty($lastMessage['data'])) {
                foreach ($lastMessage['data'] as $msg) {
                    $message = json_encode(['event' => 'user_conn', 'msg' => [$msg], 'desc' => '获取成功'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                    self::putYunXinCustomMsgQueue($msg['uid'], $msg['receive_uid'], $message);
                }
            }
        } catch (\Throwable $e) {
            LoggerUtil::write('put_yun_xin_send_gift_queue', [
                $e->getFile(), $e->getLine(), $e->getMessage()
            ]);
            return false;
        }


    }


    /**
     * Note - 批量发送系统消息
     * DateTime 2024/8/19 15:08
     * User Admin
     * @param $message
     * @param $toUids
     * @return bool
     */
    public static function putYunXinBatchSendAttachMsgQueue($message, $toUids)
    {
        try {
            $result = pushQueueMessage(YunXinBatchSendAttachMsgJob::class, compact('toUids', "message"));
            if (!$result) {
                throw new \Exception("putYunXinBatchSendAttachMsg加入发送队列失败");
            }
            return true;
        } catch (\Throwable $e) {
            LoggerUtil::write('put_yun_xin_batch_send_attach_msg', [
                $e->getFile(), $e->getLine(), $e->getMessage()
            ]);
            return false;
        }
    }


    /**
     * Note - 用户开通vip触发消息发送
     * DateTime 2024/8/21 10:50
     * User Admin
     * @param $fromUid
     * @param $content
     * @return true
     */
    public function vipEventSendMsg($fromUid, $content)
    {
        $uids = AnchorDao::getInstance()->getFemaleUids(0, 0, 1);
        foreach ($uids as $toUid) {
            self::putYunXinSendMsgQueue($fromUid, $toUid, $content, 1, 12);
        }
        return true;
    }


    /**
     * Note - 开通会员、充值金币发送给推荐主播
     * DateTime 2024/8/21 10:54
     * User Admin
     * @param $event
     * @param $uid
     * @param $session_id
     * @param $data
     * @return true
     */
    public function rechargeMsgSend($event, $uid, $session_id, $data)
    {
        $message = json_encode(array('event' => 'notice', 'data' => $data));
        // 获取推荐主播Uid
        $uids = AnchorDao::getInstance()->getFemaleUids(0, 0, 0, 0, [], 1);

        if (sizeof($uids) > 0) {
            self::putYunXinBatchSendAttachMsgQueue($message, $uids);
        }

        return true;
    }


}